package activity.addCamera;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.hichip.campro.R;
import java.util.List;
import activity.addCamera.adapter.WiFiListAdapter;
import base.HiActivity;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
/**
 * 可用 WiFi 列表界面
 * Created by lt on 2017\12\28 0028.
 */

public class PhoneWiFiListActivity extends HiActivity implements AdapterView.OnItemClickListener {
    @BindView(R.id.titleview) TitleView titleview;
    @BindView(R.id.lv_wifi_list) ListView lv_wifi_list;
    @BindView(R.id.tv_not_search_device) TextView tv_not_search_device;
    private List<ScanResult> scanResults;
    private WifiManager wifiManager;
    private WiFiListAdapter mAdapter;

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        initViewAndData();
        setListeners();

    }

    private void setListeners() {
        lv_wifi_list.setOnItemClickListener(this);
    }

    @Override
    protected int setLayoutId() {
        return R.layout.activity_phone_wifi_list;
    }

    private void initViewAndData() {
        titleview.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
//      titleview.setButton(TitleView.NAVIGATION_BUTTON_RIGHT);
        titleview.setRightTxtBack(R.mipmap.refresh_blue);
        titleview.setTitle(getString(R.string.title_select_wifi));
        initData();
        titleview.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        finish();
                        break;
                    case TitleView.NAVIGATION_BUTTON_IV_RIGHT:
                        showjuHuaDialog();
                        if (mAdapter != null) {
                            scanResults.clear();
                            lv_wifi_list.requestLayout();
                            mAdapter.notifyDataSetChanged();
                        }
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                refreshData();
                            }
                        }, 1000);
                        break;
                }
            }
        });
    }

    private void refreshData() {
        if (wifiManager != null) {
            wifiManager.startScan();
           List<ScanResult> results= wifiManager.getScanResults();
           for(int i=0;i<results.size();i++){
               ScanResult scanResult=results.get(i);
               if(scanResult.SSID.startsWith(HiDataValue.START_WITH_IPCAM)){
                   results.remove(scanResult);
               }
           }
            scanResults.addAll(results);
            if (scanResults.size() < 1) {
                tv_not_search_device.setVisibility(View.VISIBLE);
            } else {
                if (mAdapter != null) {
                    dismissjuHuaDialog();
                    lv_wifi_list.requestLayout();
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void initData() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission_group.LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 获取wifi连接需要定位权限,没有获取权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE,}, 110);
            return;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {// 允许
            wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (!wifiManager.isWifiEnabled()) {
                wifiManager.setWifiEnabled(true);
            }
            wifiManager.startScan();
            scanResults = wifiManager.getScanResults();

            RemoveIPCAM();
            if (scanResults.size() < 1) {
                tv_not_search_device.setVisibility(View.VISIBLE);
            } else {
                mAdapter = new WiFiListAdapter(PhoneWiFiListActivity.this, scanResults);
                lv_wifi_list.setAdapter(mAdapter);
            }
        } else {// 不允许
            Toast.makeText(this,getString(R.string.no_permission), Toast.LENGTH_SHORT).show();
        }
    }

    private void RemoveIPCAM() {
        for(int i=0;i<scanResults.size();i++){
            ScanResult scanResult=scanResults.get(i);
            if(scanResult.SSID.startsWith(HiDataValue.START_WITH_IPCAM)){
                scanResults.remove(scanResult);
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (scanResults != null && scanResults.size() > 0) {
            ScanResult scanResult = scanResults.get(position);
            Intent intent = new Intent();
            intent.putExtra("configssid", scanResult.SSID);
            setResult(RESULT_OK, intent);
            finish();
        }
    }
}
